/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* cur = root;
        TreeNode* maxNode;
        TreeNode* minNode;

        if ((p->val) > (q->val))
        {
            maxNode = p;
            minNode = q;
        }
        else
        {
            maxNode = q;
            minNode = p;
        }

        while (cur != maxNode && cur != minNode)
        {
            if (cur->val > maxNode->val)
                cur = cur->left;
            else if (cur->val < minNode->val)
                cur = cur->right;
            else if (cur->val<maxNode->val && cur->val>minNode->val)
                break;
        }
        return cur;
    }
};